<template>
  <div>
    <el-row :gutter="25">
      <el-col :span="3"><el-button type="primary" size="small" icon="el-icon-upload" @click="dialogTableVisible = true">上传</el-button></el-col>
      <el-dialog title="上传文件" :visible.sync="dialogTableVisible">
        <el-upload class="upload-demo" drag action  multiple :on-remove="handleRemove1" :file-list="fileList"   :limit="2" :on-exceed="handleExceed" :on-error="handleUploadError" :auto-upload="false" :on-change="fileChange"  :on-progress="uploadFileProcess">
          <i class="el-icon-upload"></i>         
          <div class="el-upload__text">将文件拖到此处自动上传或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">单次上传不能超过2个文件,每个文件不超过100MB,上传不能超过剩余容量!</div>
        </el-upload>
        <el-button  type="success" style="margin-top: 10px;" @click="uploadFile">点击上传</el-button>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleRemove" >取 消</el-button>
        </div>
      </el-dialog>
      <el-col :span="3"><el-button type="danger" icon="el-icon-delete" size="small" @click="deletefile" >删除</el-button></el-col>
      <el-col :span="3">
    </el-col>
      <el-col :span="6"><el-input placeholder="输入文件名搜索所有文件" prefix-icon="el-icon-search" v-model="input2" clearable @change="inputChange"></el-input></el-col> 
    </el-row>
    <h5>全部文件</h5>
    <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange" >
    <el-table-column type="selection" width="55" > </el-table-column>
    <el-table-column label="文件名"  show-overflow-tooltip width="260" >
      <template slot-scope="scope">
        <span style="margin-left: 10px"><el-link :icon="scope.row.fileType" :underline="false" @click="getFileInfoByPid(scope.row.fileId)">{{scope.row.fileName}}</el-link></span>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="上传日期" width="180"></el-table-column>
    <el-table-column prop="fileSize" label="文件大小" show-overflow-tooltip width="150"> </el-table-column>
    <el-table-column  label="操作" :fit="true" width="260">
      <template slot-scope="scope">
        <span>
        <el-link type="primary" style="margin-left:5px" :underline="false" icon="el-icon-share" @click="share(scope.row.fileId)">分享</el-link>
        <el-link type="success" style="margin-left:5px" :underline="false" icon="el-icon-download" @click="download(scope.row.fileId)">下载</el-link>
        <el-link type="primary" style="margin-left:10px" :underline="false" icon="el-icon-edit-outline" @click="rename(scope.row.fileId)">重命名</el-link>
        </span>   
      </template>      
    </el-table-column>
  </el-table>
  <el-pagination background layout="prev, pager, next" :total="totalnum" :page-size="pagesize" @size-change="handleSizeChange" @current-change="handleCurrentChange"  :current-page="currentpage" style="margin-top:30px;margin-left:20%">
</el-pagination>
<!-- 上传进度表 -->
<div v-if="showProgress">
  <h3>文件上传进度</h3>
      <el-progress :percentage="uploadPercentage" />
</div>
<div v-if="downloadshowProgress">
  <h3>文件下载进度</h3>
      <el-progress :percentage="downloadPercentage" />
    </div>
  </div>
</template>

<script>
 import axios from 'axios'
export default {
    data(){
    return{
      downloadshowProgress:false,
    showProgress:false,
    uploadPercentage:0,
    downloadPercentage:0,
    fileCurrentPid:'0',
    isoverSize:false,
    isovernum:false,
    dialogTableVisible:false,
    fileList: [],
    ref:`/api/uploadfile`,
    headers: { "Content-Type": "multipart/form-data" },
    input2:'',
    tableData:[],
    multipleSelection: [],
    sefileid:[],
    filetype:["","el-icon-video-play","el-icon-headset","el-icon-picture","el-icon-document","el-icon-more","el-icon-folder"],
    totalnum:0,
    currentpage:1,  //当前所在页默认是第一页
    pagesize:5,  //每页显示多少行数据 默认设置为10
    list:[],
    droplist:[],
    };
},
methods:{
     //上传了的文件给移除的事件，由于我没有用到默认的展示，所以没有用到
     handleRemove(){
      this.dialogTableVisible = false
      this.fileList = [];

    },
    handleRemove1(file,fileList){
      this.fileList = fileList;

    },
      //检测文件变动获取文件
  fileChange(file, fileList) {
    if(!this.isoverSize){
        this.isoverSize=false
      }
      if(!this.isovernum){
        this.isovernum=false
      }
    const isLt5M = file.size / 1024 / 1024 < 50; //这里做文件大小限制
        //如果大于100M
        if (!isLt5M) {
          this.$message.error("单个文件最大不能超过50MB");
          this.isoverSize=true
          this.fileList=[]
        }else{
          this.fileList = fileList;
        }
  },
      //上传文件的事件
      uploadFile(){
        this.dialogTableVisible = false
        console.log(this.fileList===null+"--------"+this.fileList)
        if(this.fileList.length===0){
          this.$message.error("先上传文件再发送到服务器哦!");
        }else{
            // 在文件上传前执行的操作
      this.showProgress = true;
      this.uploadPercentage = 0;
          this.$message({
          type:'info',
          message:'文件上传中....',
          offset:38,
          showClose: true,
        })
        //上传文件的需要formdata类型;所以要转
        let FormDatas = new FormData()
        this.fileList.forEach(file => {
          FormDatas.append('files', file.raw)
    })
        axios({
          method: 'post',
          url: `/api/uploadfile?email=${localStorage.getItem("email")}&fileIds=${this.sefileid}`,
          headers:this.headers,
          timeout: 300000,
          data: FormDatas,
          onUploadProgress:(progressEvent)=>{
            this.uploadPercentage = Math.round((progressEvent.loaded / progressEvent.total) * 100);
          }
          }).then(res=>{
            if(res.data.code == 200){
              this.fileList=[]
                    this.$message({
                    type:'success',
                    message:'上传文件成功',
                    offset:40,
                    showClose: true,
                  });
                  location.reload()
            }
            else{
              this.$message.error(res.data.message);
            }
          })
        }
      },
  share(fileId){
    this.$alert(`http://www.ishowcode.asia/api/download?fileId=${fileId}`, '下载地址', {
          confirmButtonText: '确定',
          callback: action => {
           if(action==='confirm'){
            this.$message({
                type: 'success',
                message: '快去分享给你的朋友吧'
              });
           }else{
            this.$message.error("取消分享");
           }
          }
        });
  },
  rename(fileId){
    this.$prompt('请输入修改的名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^.+$/,
          inputErrorMessage: '名称格式不正确'
        }).then(({ value }) => {
          axios.get(`/api/renameById?email=${localStorage.getItem("email")}&fileId=${fileId}&rename=${value}`).then(
            response=>{
              console.log(response)
              if(response.data.code===200){
                console.log(response.data.code)
                this.$message({
                type: 'success',
                message: '修改的文件名是: ' + value
              });
              location.reload()
              }else{
                this.$message.error(response.data.message);
              }
            },
            error=>{
              this.$message.error("修改文件名失败");
              console.log(error.$message)
            }
          )
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
  },
  download(fileId){
    if(!this.downloadshowProgress){
      this.downloadshowProgress = true
      this.downloadPercentage = 0
      axios({
    method: 'post',
    url: `/api/downloadByfileId?email=${localStorage.getItem("email")}&fileId=${fileId}`,
    // 二进制流文件，一定要设置成blob，默认是json
    responseType: 'blob',
    onDownloadProgress: progressEvent => {
          this.downloadPercentage = Math.round((progressEvent.loaded / progressEvent.total) * 100);
        }
  }).then(
    res => {
      if(res.status===200){
        let blob = new Blob([res.data])
        let contentDisposition = res.headers['content-disposition']
        let pattern = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
        let result = pattern.exec(contentDisposition)
        // 使用decodeURI对名字进行解码
        console.log(result)
        let fileName = decodeURI(result[1])
        let downloadElement = document.createElement('a')
        // 创建下载的链接
        let href = window.URL.createObjectURL(blob)
        downloadElement.style.display = 'none'
        downloadElement.href = href
        // 下载后文件名
        downloadElement.download = fileName
        document.body.appendChild(downloadElement)
        // 点击下载
        downloadElement.click()
        // 下载完成移除元素
        document.body.removeChild(downloadElement)
        // 释放掉blob对象
        window.URL.revokeObjectURL(href)
        this.$message({
            type: 'success',
            message: '文件下载成功!'
          });
       this.downloadshowProgress = false
      this.downloadPercentage = 0
      }else{
        this.$message.error("文件下载失败")
      }

      }
  )
    }else{
      this.$message.error("已经有任务在下载哦!")
    }
  },
  onVisibleChange(val){
    if(val){
     
      axios.get(`/api/getfolder?email=${localStorage.getItem("email")}`).then(
      response=>{
        if(response.data.code==200){
          this.droplist = response.data.data
        }else{        
          this.$message.error("文件夹列表显示失败")
        }
      },
      error=>{
        this.$message.error("文件夹列表显示失败");
        console.log(error.$message)
      }
      )
    }else{
      this.droplist = []
    }

  },
   //分页时修改每页的行数,这里会自动传入一个size
   handleSizeChange(size){
      //修改当前每页的数据行数
      this.pagesize=size;
      //数据重新分页
      this.getPageInfo();
    },
    //调整当前的页码
    handleCurrentChange(pageNumber){
      //修改当前的页码
      this.currentpage=pageNumber;
      //数据重新分页
      this.getPageInfo()
  },
  getPageInfo(){
    //清空列表
    this.tableData = []
     // 获取当前页的数据
     for(let i=(this.currentpage-1)*this.pagesize;i<this.totalnum;i++){
        //把遍历的数据添加到pageTicket里面
        this.tableData.push(this.list[i]);
        //判断是否达到一页的要求
        if(this.tableData.length===this.pagesize) break;
      }
  },
  inputChange(){
    if(localStorage.getItem("email")!==null){
        axios.get(`/api/getFileByType?email=${localStorage.getItem("email")}&type=4&input=${this.input2}`).then(
      response=>{
        if(response.data.code==200){
           this.list = response.data.data.fileList
          this.totalnum = this.list.length
          for (let item in this.list) {
            this.list[item].fileType = this.filetype[this.list[item].fileType]
            //不足1KB
            if(this.list[item].fileSize<1024){
              let Bsize = this.list[item].fileSize+'B'
              this.list[item].fileSize=Bsize
            }
            //不足1MB
            else if(this.list[item].fileSize>=1024&&this.list[item].fileSize<1024*1024){
              let Ksize = (this.list[item].fileSize/1024).toFixed(3)+'KB'
              this.list[item].fileSize=Ksize
            }
            //不足1GB
            else if(this.list[item].fileSize>=1024*1024&&this.list[item].fileSize<1024*1024*1024){
              let Msize = (this.list[item].fileSize/(1024*1024)).toFixed(3)+'MB'
              this.list[item].fileSize=Msize
            }else{
              let Gsize = (this.list[item].fileSize/(1024*1024*1024)).toFixed(3)+'GB'
              this.list[item].fileSize=Gsize
            }
          }
        this.getPageInfo()
        }else{        
          this.$message.error("文件列表显示失败")
        }
      },
      error=>{
        this.$message.error("文件列表显示失败");
        console.log(error.$message)
      }
    )
      }

  },
  deletefile(){
    this.$confirm('此操作将删除所选的文件或文件夹内所有文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.get(`/api/deleteById?email=${localStorage.getItem("email")}&fileIds=${this.sefileid}`).then(
      response=>{
        if(response.data.code==200){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          location.reload()
        }else{
          this.$message.error(response.data.message)
        }
      },
      error=>{
        this.$message.error("删除失败");
        console.log(error.$message)
      }
    )         
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
  },
  handleSelectionChange(val) {
        this.sefileid=[]
        this.multipleSelection = val;
        for (const key in this.multipleSelection) {
          this.sefileid[key] = this.multipleSelection[key].fileId
        }
      },
      //上传文件之前
    beforeUpload(file){
      if(!this.isoverSize){
        this.isoverSize=false
      }
      if(!this.isovernum){
        this.isovernum=false
      }
        const isLt5M = file.size / 1024 / 1024 < 100; //这里做文件大小限制
        //如果大于100M
        if (!isLt5M) {
          this.$message.error("单个文件最大不能超过100MB");
          this.isoverSize=true
          return false
        }
      return true
    },
    handleExceed(){
      this.$message.error(`一次只允许上传2个文件`);
      this.isovernum=true
    },
          // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
      console.log(err.$message)
    },
    },
    mounted(){
      if(localStorage.getItem("email")!==null){
        axios.get(`/api/getFileByType?email=${localStorage.getItem("email")}&type=4&input=${this.input2}`).then(
      response=>{
        if(response.data.code==200){
           this.list = response.data.data.fileList
          this.totalnum = this.list.length
          for (let item in this.list) {
            this.list[item].fileType = this.filetype[this.list[item].fileType]
            //不足1KB
            if(this.list[item].fileSize<1024){
              let Bsize = this.list[item].fileSize+'B'
              this.list[item].fileSize=Bsize
            }
            //不足1MB
            else if(this.list[item].fileSize>=1024&&this.list[item].fileSize<1024*1024){
              let Ksize = (this.list[item].fileSize/1024).toFixed(3)+'KB'
              this.list[item].fileSize=Ksize
            }
            //不足1GB
            else if(this.list[item].fileSize>=1024*1024&&this.list[item].fileSize<1024*1024*1024){
              let Msize = (this.list[item].fileSize/(1024*1024)).toFixed(3)+'MB'
              this.list[item].fileSize=Msize
            }else{
              let Gsize = (this.list[item].fileSize/(1024*1024*1024)).toFixed(3)+'GB'
              this.list[item].fileSize=Gsize
            }
          }
        this.getPageInfo()
        }else{        
          this.$message.error(response.data.message)
        }
      },
      error=>{
        this.$message.error("文件列表显示失败");
        console.log(error.$message)
      }
    )
      }

    }

    }
</script>

<style>

</style>